package com.cvte.sunkit.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.database.DataSetObserver
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.SpinnerAdapter
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSpinner
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.cvte.sunkit.App
import com.cvte.sunkit.R
import com.cvte.sunkit.databinding.ActivityChoseBinding
import com.cvte.sunkit.ui.base.BaseActivity
import java.lang.Package.getPackages


/**
 *
 * 选择应用列表界面
 */
class ChoseActivity : BaseActivity() {

    private lateinit var mBinding: ActivityChoseBinding
    private lateinit var mSpinner: AppCompatSpinner
    private lateinit var mListPack: List<ApplicationInfo> // 获取应用包名列表

    companion object {
        private const val TAG = "ChoseActivity"
        fun actionStart(context: Context) {
            val intent = Intent(context, ChoseActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityChoseBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        initView()
//        Log.i(TAG, "onCreate: $mListPack")
    }

    private fun initView() {
        mBinding.headerTitle.txtTitle.text = "性能测试"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (ContextCompat.checkSelfPermission(
                    this, Manifest.permission.QUERY_ALL_PACKAGES
                ) == PackageManager.PERMISSION_GRANTED
            ) { // 已授权
                mListPack = App.mInstance.loadAppList()
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.QUERY_ALL_PACKAGES),
                    1
                )
            }
        } else {
            mListPack = App.mInstance.loadAppList() // Android 版本低于 11，直接获取包名列表
        }

        mSpinner = mBinding.choseAppSpinner
        mSpinner.adapter = (object : SpinnerAdapter {
            override fun registerDataSetObserver(p0: DataSetObserver?) {
            }

            override fun unregisterDataSetObserver(p0: DataSetObserver?) {
            }

            override fun getCount() = mListPack.size + 1

            override fun getItem(p0: Int) {
                mListPack[p0 - 1]
            }

            override fun getItemId(p0: Int): Long = p0.toLong()

            override fun hasStableIds(): Boolean = false

            override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View? {
                return getDropDownView(p0, p1, p2)
            }

            override fun getItemViewType(p0: Int) = 0

            override fun getViewTypeCount() = 1

            override fun isEmpty() = false

            @SuppressLint("InflateParams")
            override fun getDropDownView(position: Int, v: View?, viewGroup: ViewGroup?): View? {
                var view = v
                if (view == null) {
                    view = LayoutInflater.from(this@ChoseActivity)
                        .inflate(R.layout.item_chose_app, null)
                }
                if (position == 0) {
                    view?.findViewById<ImageView>(R.id.choose_icon)
                        ?.setImageResource(R.drawable.ic_launcher_background)
                    view?.findViewById<TextView>(R.id.choose_title)?.text = "全局"
                } else {
                    val info = mListPack[position - 1]
                    val appImg: ImageView? = view?.findViewById(R.id.choose_icon)
                    appImg.let {
                        if (it != null) {
                            Glide.with(this@ChoseActivity).load(info.packageName).into(it)
                        }
                    }
                    view?.findViewById<TextView>(R.id.choose_title)?.text =
                        info.loadLabel(packageManager).toString()
                    view?.findViewById<TextView>(R.id.choose_activity)?.text = info.packageName
                }
                return view
            }

        })
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 检查权限授予结果
                getPackages() // 权限已被授予
            } else {
                Log.d(TAG, "Permission denied") // 权限被拒绝
            }
        }
    }

}